{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quickstart: Semantic ranking in Azure AI Search"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Azure AI Search supports secondary L2 ranking that rescores initial results using machine reading comprehension models. The L2 ranker promotes more semantically relevant matches to the top.\n",
    "\n",
    "This is the source code for the article: [Quickstart: Semantic ranking (Python)](https://learn.microsoft.com/azure/search/search-get-started-semantic)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install packages and set variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install -r requirements.txt --quiet"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Provide variables\n",
    "from dotenv import load_dotenv\n",
    "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
    "import os\n",
    "\n",
    "load_dotenv(override=True) # Take environment variables from .env.\n",
    "\n",
    "# The following variables from your .env file are used in this notebook\n",
    "search_endpoint = os.environ[\"AZURE_SEARCH_ENDPOINT\"]\n",
    "credential = DefaultAzureCredential()\n",
    "token_provider = get_bearer_token_provider(credential, \"https://search.azure.com/.default\")\n",
    "index_name = os.getenv(\"AZURE_SEARCH_INDEX\", \"hotels-sample-index\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get the index definition\n",
    "\n",
    "This code retrieves the hotels-sample-index and checks for an existing semantic configuration. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index name: hotels-sample-index\n",
      "Number of fields: 14\n",
      "Field: HotelId, Type: Edm.String, Searchable: False\n",
      "Field: HotelName, Type: Edm.String, Searchable: True\n",
      "Field: Description, Type: Edm.String, Searchable: True\n",
      "Field: Description_fr, Type: Edm.String, Searchable: True\n",
      "Field: Category, Type: Edm.String, Searchable: True\n",
      "Field: Tags, Type: Collection(Edm.String), Searchable: True\n",
      "Field: ParkingIncluded, Type: Edm.Boolean, Searchable: False\n",
      "Field: LastRenovationDate, Type: Edm.DateTimeOffset, Searchable: False\n",
      "Field: Rating, Type: Edm.Double, Searchable: False\n",
      "Field: Address, Type: Edm.ComplexType, Searchable: None\n",
      "Field: Location, Type: Edm.GeographyPoint, Searchable: False\n",
      "Field: Rooms, Type: Collection(Edm.ComplexType), Searchable: None\n",
      "Field: id, Type: Edm.String, Searchable: False\n",
      "Field: rid, Type: Edm.String, Searchable: False\n",
      "No semantic configuration exists for this index\n"
     ]
    }
   ],
   "source": [
    "from azure.search.documents.indexes import SearchIndexClient\n",
    "from azure.identity import DefaultAzureCredential\n",
    "import os\n",
    "\n",
    "# Initialize the client (similar to what you already have)\n",
    "search_endpoint = os.environ[\"AZURE_SEARCH_ENDPOINT\"]\n",
    "credential = DefaultAzureCredential()\n",
    "index_name = \"hotels-sample-index\"  # or use your existing index_name variable\n",
    "\n",
    "# Create the SearchIndexClient\n",
    "index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)\n",
    "\n",
    "try:\n",
    "    # Get the existing index schema\n",
    "    index = index_client.get_index(index_name)\n",
    "    \n",
    "    print(f\"Index name: {index.name}\")\n",
    "    print(f\"Number of fields: {len(index.fields)}\")\n",
    "    \n",
    "    # Print field details\n",
    "    for field in index.fields:\n",
    "        print(f\"Field: {field.name}, Type: {field.type}, Searchable: {field.searchable}\")\n",
    "    \n",
    "    # Access semantic configuration if it exists\n",
    "    if index.semantic_search and index.semantic_search.configurations:\n",
    "        for config in index.semantic_search.configurations:\n",
    "            print(f\"Semantic config: {config.name}\")\n",
    "            if config.prioritized_fields.title_field:\n",
    "                print(f\"Title field: {config.prioritized_fields.title_field.field_name}\")\n",
    "    else:\n",
    "        print(\"No semantic configuration exists for this index\")\n",
    "\n",
    "except Exception as ex:\n",
    "    print(f\"Error retrieving index: {ex}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add a semantic configuration to the index\n",
    "\n",
    "This code adds a semantic configuration to an existing hotels-sample-index on your search service. No search documents are deleted by this operation and your index is still operational after the configuration is added."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Semantic configurations:\n",
      "----------------------------------------\n",
      "  Configuration: semantic-config\n",
      "    Title field: HotelName\n",
      "    Keywords fields: Tags\n",
      "    Content fields: Description\n",
      "\n",
      "✅ Semantic configuration successfully added!\n"
     ]
    }
   ],
   "source": [
    "# Add semantic configuration to hotels-sample-index and display updated index details\n",
    "from azure.search.documents.indexes.models import (\n",
    "    SemanticConfiguration,\n",
    "    SemanticField,\n",
    "    SemanticPrioritizedFields,\n",
    "    SemanticSearch\n",
    ")\n",
    "\n",
    "try:\n",
    "    # Get the existing index\n",
    "    existing_index = index_client.get_index(index_name)\n",
    "    \n",
    "    # Create a new semantic configuration\n",
    "    new_semantic_config = SemanticConfiguration(\n",
    "        name=\"semantic-config\",\n",
    "        prioritized_fields=SemanticPrioritizedFields(\n",
    "            title_field=SemanticField(field_name=\"HotelName\"),\n",
    "            keywords_fields=[SemanticField(field_name=\"Tags\")],\n",
    "            content_fields=[SemanticField(field_name=\"Description\")]\n",
    "        )\n",
    "    )\n",
    "    \n",
    "    # Add semantic configuration to the index\n",
    "    if existing_index.semantic_search is None:\n",
    "        existing_index.semantic_search = SemanticSearch(configurations=[new_semantic_config])\n",
    "    else:\n",
    "        # Check if configuration already exists\n",
    "        config_exists = any(config.name == \"semantic-config\" \n",
    "                          for config in existing_index.semantic_search.configurations)\n",
    "        if not config_exists:\n",
    "            existing_index.semantic_search.configurations.append(new_semantic_config)\n",
    "    \n",
    "    # Update the index\n",
    "    result = index_client.create_or_update_index(existing_index)\n",
    "    \n",
    "    # Get the updated index and display detailed information\n",
    "    updated_index = index_client.get_index(index_name)\n",
    "    \n",
    "    print(\"Semantic configurations:\")\n",
    "    print(\"-\" * 40)\n",
    "    if updated_index.semantic_search and updated_index.semantic_search.configurations:\n",
    "        for config in updated_index.semantic_search.configurations:\n",
    "            print(f\"  Configuration: {config.name}\")\n",
    "            if config.prioritized_fields.title_field:\n",
    "                print(f\"    Title field: {config.prioritized_fields.title_field.field_name}\")\n",
    "            if config.prioritized_fields.keywords_fields:\n",
    "                keywords = [kf.field_name for kf in config.prioritized_fields.keywords_fields]\n",
    "                print(f\"    Keywords fields: {', '.join(keywords)}\")\n",
    "            if config.prioritized_fields.content_fields:\n",
    "                content = [cf.field_name for cf in config.prioritized_fields.content_fields]\n",
    "                print(f\"    Content fields: {', '.join(content)}\")\n",
    "            print()\n",
    "    else:\n",
    "        print(\"  No semantic configurations found\")\n",
    "    \n",
    "    print(\"✅ Semantic configuration successfully added!\")\n",
    "    \n",
    "except Exception as ex:\n",
    "    print(f\"❌ Error adding semantic configuration: {ex}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run a term query\n",
    "\n",
    "Your first query is a keyword search, specified by `query_type` set to simple. For comparison, run this query to review the results when no semantic ranking is used. This query has search text, which provides criteria for potential matches. Output should consist of 13 documents containing literal or variant instances of the search terms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.5153193\n",
      "2\n",
      "Old Century Hotel\n",
      "Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.\n",
      "5.074317\n",
      "24\n",
      "Uptown Chic Hotel\n",
      "Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.\n",
      "4.8959594\n",
      "4\n",
      "Sublime Palace Hotel\n",
      "Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.\n",
      "2.5966604\n",
      "35\n",
      "Bellevue Suites\n",
      "Description: Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n",
      "2.566386\n",
      "47\n",
      "Country Comfort Inn\n",
      "Description: Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome.\n",
      "2.2405157\n",
      "9\n",
      "Smile Up Hotel\n",
      "Description: Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene.\n",
      "2.1737604\n",
      "8\n",
      "Foot Happy Suites\n",
      "Description: Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further.\n",
      "2.0364518\n",
      "31\n",
      "Country Residence Hotel\n",
      "Description: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door.\n",
      "1.7595702\n",
      "49\n",
      "Swirling Currents Hotel\n",
      "Description: Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. \n",
      "1.5502293\n",
      "15\n",
      "By the Market Hotel\n",
      "Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.\n",
      "1.3302404\n",
      "42\n",
      "Rock Bottom Resort & Campground\n",
      "Description: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "0.9050383\n",
      "38\n",
      "Lakeside B & B\n",
      "Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "0.7334347\n",
      "39\n",
      "White Mountain Lodge & Suites\n",
      "Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.\n"
     ]
    }
   ],
   "source": [
    "from azure.search.documents import SearchClient\n",
    "\n",
    "# Create the SearchIClient\n",
    "search_client = SearchClient(endpoint=search_endpoint, credential=credential, index_name=index_name)\n",
    "\n",
    "# Run a text query (returns a BM25-scored result set)\n",
    "results =  search_client.search(query_type='simple',\n",
    "    search_text=\"walking distance to live music\" ,\n",
    "    select='HotelId,HotelName,Description',\n",
    "    include_total_count=True)\n",
    "    \n",
    "for result in results:\n",
    "    print(result[\"@search.score\"])\n",
    "    print(result[\"HotelId\"])\n",
    "    print(result[\"HotelName\"])\n",
    "    print(f\"Description: {result['Description']}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run a semantic query\n",
    "\n",
    "This example sets `query_type` to semantic. Compared to the previous query, the L2 ranker revisits the search results and rescores them using machine reading comprehension models, promoting results that are more meaningful to the query. Output should consist of 13 documents in a revised ranking. The effect of semantic ranking is apparent in the top half of the results, where results in positions four through six are more semantically aligned with the search text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.613231658935547\n",
      "24\n",
      "Uptown Chic Hotel\n",
      "Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.\n",
      "2.271434783935547\n",
      "2\n",
      "Old Century Hotel\n",
      "Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.\n",
      "1.9861756563186646\n",
      "4\n",
      "Sublime Palace Hotel\n",
      "Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.\n",
      "1.9615401029586792\n",
      "39\n",
      "White Mountain Lodge & Suites\n",
      "Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.\n",
      "1.9085469245910645\n",
      "15\n",
      "By the Market Hotel\n",
      "Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.\n",
      "1.90234375\n",
      "49\n",
      "Swirling Currents Hotel\n",
      "Description: Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. \n",
      "1.9012802839279175\n",
      "31\n",
      "Country Residence Hotel\n",
      "Description: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door.\n",
      "1.896849513053894\n",
      "9\n",
      "Smile Up Hotel\n",
      "Description: Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene.\n",
      "1.6703436374664307\n",
      "8\n",
      "Foot Happy Suites\n",
      "Description: Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further.\n",
      "1.5264291763305664\n",
      "47\n",
      "Country Comfort Inn\n",
      "Description: Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome.\n",
      "1.4590801000595093\n",
      "42\n",
      "Rock Bottom Resort & Campground\n",
      "Description: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "1.4512817859649658\n",
      "38\n",
      "Lakeside B & B\n",
      "Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "1.2407270669937134\n",
      "35\n",
      "Bellevue Suites\n",
      "Description: Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n"
     ]
    }
   ],
   "source": [
    "# Runs a semantic query (runs a BM25-ranked query and promotes the most relevant matches to the top)\n",
    "results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',\n",
    "    search_text=\"walking distance to live music\", \n",
    "    select='HotelId,HotelName,Description', query_caption='extractive')\n",
    "\n",
    "for result in results:\n",
    "    print(result[\"@search.reranker_score\"])\n",
    "    print(result[\"HotelId\"])\n",
    "    print(result[\"HotelName\"])\n",
    "    print(f\"Description: {result['Description']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Return captions\n",
    "\n",
    "A semantic query can return captions, or a portion of the matching text. Captions are useful if content is verbose or if you want hit highlights in the results.\n",
    "\n",
    "In shorter descriptions like the ones in this sample index, captions are less useful and you might consider omitting them if they don't add value to your solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.613231658935547\n",
      "24\n",
      "Uptown Chic Hotel\n",
      "Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.\n",
      "Caption: Chic hotel near the city. High-rise hotel in downtown, within walking distance to<em> theaters, </em>art galleries, restaurants and shops. Visit<em> Seattle Art Museum </em>by day, and then head over to<em> Benaroya Hall </em>to catch the evening's concert performance.\n",
      "\n",
      "2.271434783935547\n",
      "2\n",
      "Old Century Hotel\n",
      "Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.\n",
      "Caption: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live.\n",
      "\n",
      "1.9861756563186646\n",
      "4\n",
      "Sublime Palace Hotel\n",
      "Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.\n",
      "Caption: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within<em> short walking distance </em>to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort,.\n",
      "\n",
      "1.9615401029586792\n",
      "39\n",
      "White Mountain Lodge & Suites\n",
      "Description: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.\n",
      "Caption: Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend<em> evening entertainment </em>on the patio features special<em> guest musicians </em>or.\n",
      "\n",
      "1.9085469245910645\n",
      "15\n",
      "By the Market Hotel\n",
      "Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.\n",
      "Caption: Book now and Save up to 30%. Central location. <em>Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood.</em> Brand new rooms. Impeccable service.\n",
      "\n",
      "1.90234375\n",
      "49\n",
      "Swirling Currents Hotel\n",
      "Description: Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. \n",
      "Caption: Spacious rooms, glamorous suites and residences, rooftop pool,<em> walking access </em>to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs.\n",
      "\n",
      "1.9012802839279175\n",
      "31\n",
      "Country Residence Hotel\n",
      "Description: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door.\n",
      "Caption: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant<em> music scene </em>in the world is<em> just outside your front door.</em>\n",
      "\n",
      "1.896849513053894\n",
      "9\n",
      "Smile Up Hotel\n",
      "Description: Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene.\n",
      "Caption: Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our<em> weekend live music series </em>featuring who's new/next on the scene.\n",
      "\n",
      "1.6703436374664307\n",
      "8\n",
      "Foot Happy Suites\n",
      "Description: Downtown in the heart of the business district. Close to everything. Leave your car behind and walk to the park, shopping, and restaurants. Or grab one of our bikes and take your explorations a little further.\n",
      "Caption: Downtown in the heart of the business district. Close to everything. <em>Leave your car behind and walk to the park, shopping, </em>and restaurants. Or grab one of our bikes and take your explorations a little further.\n",
      "\n",
      "1.5264291763305664\n",
      "47\n",
      "Country Comfort Inn\n",
      "Description: Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome.\n",
      "Caption: Situated conveniently at the north end of the village, the inn is just a<em> short walk from the lake, </em>offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome.\n",
      "\n",
      "1.4590801000595093\n",
      "42\n",
      "Rock Bottom Resort & Campground\n",
      "Description: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "Caption: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock<em> Bottom Lake.</em> We feature both lodging and<em> campground accommodations </em>to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "\n",
      "1.4512817859649658\n",
      "38\n",
      "Lakeside B & B\n",
      "Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "Caption: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone<em> fireplace, </em>sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "\n",
      "1.2407270669937134\n",
      "35\n",
      "Bellevue Suites\n",
      "Description: Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n",
      "Caption: Comfortable city living in the very center of<em> downtown </em>Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Runs a semantic query that returns captions\n",
    "results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',\n",
    "    search_text=\"walking distance to live music\", \n",
    "    select='HotelId,HotelName,Description', query_caption='extractive')\n",
    "\n",
    "for result in results:\n",
    "    print(result[\"@search.reranker_score\"])\n",
    "    print(result[\"HotelId\"])\n",
    "    print(result[\"HotelName\"])\n",
    "    print(f\"Description: {result['Description']}\")\n",
    "\n",
    "    captions = result[\"@search.captions\"]\n",
    "    if captions:\n",
    "        caption = captions[0]\n",
    "        if caption.highlights:\n",
    "            print(f\"Caption: {caption.highlights}\\n\")\n",
    "        else:\n",
    "            print(f\"Caption: {caption.text}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Return semantic answers\n",
    "\n",
    "A semantic query response can also includes \"answers\". This capability is useful if your index contains verbatim content that has the characteristics of a complete answer. To get an answer, the query must have the characteristics of a question, such as \"what is\" or \"when is\".\n",
    "\n",
    "To meet the requirements of semantic answers, provide a query that asks a question.\n",
    "\n",
    "Recall that answers are verbatim content pulled from your index. To get composed answers as generated by a chat completion model, considering using a [RAG pattern](https://learn.microsoft.com/azure/search/retrieval-augmented-generation-overview) or [agentic retrieval](https://learn.microsoft.com/azure/search/search-agentic-retrieval-concept)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Semantic Answer: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "Semantic Answer Score: 0.9829999804496765\n",
      "\n",
      "2.124817371368408\n",
      "1\n",
      "Stay-Kay City Hotel\n",
      "Description: This classic hotel is fully-refurbished and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.\n",
      "Caption: This classic hotel is<em> fully-refurbished </em>and ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Times Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.\n",
      "\n",
      "2.0705394744873047\n",
      "16\n",
      "Double Sanctuary Resort\n",
      "Description: 5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.\n",
      "Caption: <em>5 star Luxury Hotel </em>-<em> Biggest </em>Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.\n",
      "\n",
      "2.041472911834717\n",
      "38\n",
      "Lakeside B & B\n",
      "Description: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the library by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "Caption: Nature is Home on the beach. Explore the shore by day, and then come home to our shared living space to relax around a stone fireplace, sip something warm, and explore the<em> library </em>by night. Save up to 30 percent. Valid Now through the end of the year. Restrictions and blackouts may apply.\n",
      "\n",
      "2.0231292247772217\n",
      "2\n",
      "Old Century Hotel\n",
      "Description: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live music.\n",
      "Caption: The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts. The hotel also regularly hosts events like wine tastings, beer dinners, and live.\n",
      "\n",
      "2.021622657775879\n",
      "15\n",
      "By the Market Hotel\n",
      "Description: Book now and Save up to 30%. Central location. Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood. Brand new rooms. Impeccable service.\n",
      "Caption: Book now and Save up to 30%. <em>Central location.</em> <em>Walking distance from the Empire State Building & Times Square, in the Chelsea neighborhood.</em> Brand new rooms. Impeccable service.\n",
      "\n",
      "2.005582809448242\n",
      "5\n",
      "Red Tide Hotel\n",
      "Description: On entering this charming hotel in Scarlet Harbor, you'll notice an uncommon blend of antiques, original artwork, and contemporary comforts that give this hotel its signature look. Each suite is furnished to accentuate the views and unique characteristics of the building's classic architecture. No two suites are alike. However, all guests are welcome in the mezzanine plaza, the surrounding gardens, and the northside terrace for evening refreshments.\n",
      "Caption: On entering this charming hotel in<em> Scarlet Harbor, </em>you'll notice an uncommon blend of antiques, original artwork, and contemporary comforts that give this hotel its signature look. Each suite is furnished to accentuate the views and unique characteristics of the building's classic architecture. No two suites are alike. However, all guests are.\n",
      "\n",
      "1.9739465713500977\n",
      "24\n",
      "Uptown Chic Hotel\n",
      "Description: Chic hotel near the city. High-rise hotel in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.\n",
      "Caption: Chic hotel near the city. <em>High-rise hotel </em>in downtown, within walking distance to theaters, art galleries, restaurants and shops. Visit Seattle Art Museum by day, and then head over to Benaroya Hall to catch the evening's concert performance.\n",
      "\n",
      "1.9714652299880981\n",
      "4\n",
      "Sublime Palace Hotel\n",
      "Description: Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort, updated for every modern convenience.\n",
      "Caption: <em>Sublime Cliff Hotel </em>is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 19th century resort,.\n",
      "\n",
      "1.9443483352661133\n",
      "9\n",
      "Smile Up Hotel\n",
      "Description: Experience the fresh, modern downtown. Enjoy updated rooms, bold style & prime location. Don't miss our weekend live music series featuring who's new/next on the scene.\n",
      "Caption: Experience the fresh, modern downtown. Enjoy<em> updated rooms, bold style & prime location.</em> Don't miss our weekend live music series featuring who's new/next on the scene.\n",
      "\n",
      "1.9376134872436523\n",
      "50\n",
      "Head Wind Resort\n",
      "Description: The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.\n",
      "Caption: The best of<em> old town </em>hospitality combined with views of the river and cool breezes off the prairie. Our<em> penthouse suites </em>offer views for miles and the rooftop<em> plaza </em>is open to all guests from sunset to 10 p.m. Enjoy a complimentary<em> continental breakfast </em>in the lobby, and free Wi-Fi throughout the hotel.\n",
      "\n",
      "1.896317720413208\n",
      "28\n",
      "City Center Summer Wind Resort\n",
      "Description: Eco-friendly from our gardens to table, with a rooftop serenity pool and outdoor seating to take in the sunset. Just steps away from the Convention Center. Located in the heart of downtown with modern rooms with stunning city views, 24-7 dining options, free WiFi and easy valet parking.\n",
      "Caption: <em>Eco-friendly </em>from our gardens to table, with a<em> rooftop serenity pool and outdoor seating </em>to take in the sunset. Just steps away from the Convention Center. Located in the heart of downtown with modern rooms with stunning city views, 24-7 dining options, free WiFi and easy valet parking.\n",
      "\n",
      "1.8764674663543701\n",
      "32\n",
      "Gold View Inn\n",
      "Description: AAA Four Diamond Resort. Nestled on six beautifully landscaped acres, located 2 blocks from the park. Unwind at the spa and indulge in art tours on site.\n",
      "Caption: <em>AAA Four Diamond Resort.</em> Nestled on six beautifully landscaped acres, located 2 blocks from the park. Unwind at the spa and indulge in art tours on site.\n",
      "\n",
      "1.8688464164733887\n",
      "14\n",
      "Twin Vortex Hotel\n",
      "Description: New experience in the making. Be the first to experience the luxury of the Twin Vortex. Reserve one of our newly-renovated guest rooms today.\n",
      "Caption: New experience in the making. Be the first to experience the<em> luxury </em>of the<em> Twin Vortex.</em> Reserve one of our newly-renovated guest rooms today.\n",
      "\n",
      "1.8681374788284302\n",
      "49\n",
      "Swirling Currents Hotel\n",
      "Description: Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs. \n",
      "Caption: <em>Spacious rooms, glamorous suites and residences, rooftop pool, </em>walking access to shopping, dining, entertainment and the city center. Each room comes equipped with a microwave, a coffee maker and a minifridge. In-room entertainment includes complimentary W-Fi and flat-screen TVs.\n",
      "\n",
      "1.8596302270889282\n",
      "27\n",
      "Starlight Suites\n",
      "Description: Complimentary Airport Shuttle & WiFi. Book Now and save - Spacious All Suite Hotel, Indoor Outdoor Pool, Fitness Center, Florida Green certified, Complimentary Coffee, HDTV\n",
      "Caption: Complimentary Airport Shuttle & WiFi. <em>Book </em>Now and save -<em> Spacious All Suite Hotel, Indoor Outdoor Pool, Fitness Center, Florida Green certified, Complimentary Coffee, HDTV.</em>\n",
      "\n",
      "1.8560855388641357\n",
      "41\n",
      "Windy Ocean Motel\n",
      "Description: Oceanfront hotel overlooking the beach features rooms with a private balcony and 2 indoor and outdoor pools. Inspired by the natural beauty of the island, each room includes an original painting of local scenes by the owner. Rooms include a mini fridge, Keurig coffee maker, and flatscreen TV. Various shops and art entertainment are on the boardwalk, just steps away.\n",
      "Caption: Oceanfront hotel overlooking the beach features rooms with a private balcony and 2 indoor and outdoor pools. Inspired by the natural beauty of the island, each room includes an original painting of local scenes by the owner. Rooms include a mini fridge, Keurig coffee maker, and flatscreen TV. Various shops and art entertainment are on the.\n",
      "\n",
      "1.8536041975021362\n",
      "36\n",
      "Hotel on the Harbor\n",
      "Description: Stunning Downtown Hotel with indoor Pool. Ideally located close to theatres, museums and the convention center. Indoor Pool and Sauna and fitness centre. Popular Bar & Restaurant\n",
      "Caption: <em>Stunning Downtown Hotel </em>with<em> indoor Pool.</em> Ideally located close to theatres, museums and the convention center. Indoor Pool and Sauna and fitness centre. Popular Bar & Restaurant.\n",
      "\n",
      "1.8502367734909058\n",
      "17\n",
      "City Skyline Antiquity Hotel\n",
      "Description: In vogue since 1888, the Antiquity Hotel takes you back to bygone era. From the crystal chandeliers that adorn the Green Room, to the arched ceilings of the Grand Hall, the elegance of old New York beckons. Elevate Your Experience. Upgrade to a premiere city skyline view for less, where old world charm combines with dramatic views of the city, local cathedral and midtown.\n",
      "Caption: In vogue since 1888, the<em> Antiquity Hotel </em>takes you back to bygone era. From the crystal chandeliers that adorn the Green Room, to the arched ceilings of the Grand Hall, the elegance of old New York beckons. Elevate Your Experience. Upgrade to a premiere city skyline view for less, where old world charm combines with dramatic views of the city,.\n",
      "\n",
      "1.8397799730300903\n",
      "23\n",
      "Downtown Mix Hotel\n",
      "Description: Mix and mingle in the heart of the city. Shop and dine, mix and mingle in the heart of downtown, where fab lake views unite with a cheeky design.\n",
      "Caption: Mix and mingle in the heart of the city. Shop and dine, mix and mingle in the heart of downtown, where<em> fab lake views </em>unite with a<em> cheeky design.</em>\n",
      "\n",
      "1.8323360681533813\n",
      "18\n",
      "Ocean Water Resort & Spa\n",
      "Description: New Luxury Hotel for the vacation of a lifetime. Bay views from every room, location near the pier, rooftop pool, waterfront dining & more.\n",
      "Caption: New<em> Luxury Hotel </em>for the vacation of a lifetime. Bay views from every room, location near the pier, rooftop pool, waterfront dining & more.\n",
      "\n",
      "1.8275507688522339\n",
      "31\n",
      "Country Residence Hotel\n",
      "Description: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real country hospitality in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door.\n",
      "Caption: All of the suites feature full-sized kitchens stocked with cookware, separate living and sleeping areas and sofa beds. Some of the larger rooms have fireplaces and patios or balconies. Experience real<em> country hospitality </em>in the heart of bustling Nashville. The most vibrant music scene in the world is just outside your front door.\n",
      "\n",
      "1.8022061586380005\n",
      "29\n",
      "Treehouse Hotel\n",
      "Description: Near the beating heart of our vibrant downtown and bustling business district. Experience the warmth of our hotel. Enjoy free WiFi, local transportation and Milk & Cookies.\n",
      "Caption: Near the beating heart of our vibrant<em> downtown and bustling business district.</em> Experience the warmth of our hotel. Enjoy free WiFi, local transportation and Milk & Cookies.\n",
      "\n",
      "1.7795201539993286\n",
      "35\n",
      "Bellevue Suites\n",
      "Description: Comfortable city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n",
      "Caption: <em>Comfortable </em>city living in the very center of downtown Bellevue. Newly reimagined, this hotel features apartment-style suites with sleeping, living and work spaces. Located across the street from the Light Rail to downtown. Free shuttle to the airport.\n",
      "\n",
      "1.7795201539993286\n",
      "37\n",
      "Campus Commander Hotel\n",
      "Description: Easy access to campus and steps away from the best shopping corridor in the city. From meetings in town or gameday, enjoy our prime location between the union and proximity to the university stadium.\n",
      "Caption: <em>Easy access </em>to<em> campus </em>and steps away from the best<em> shopping corridor </em>in the city. From meetings in town or gameday, enjoy our prime location between the union and proximity to the university stadium.\n",
      "\n",
      "1.7745575904846191\n",
      "10\n",
      "Countryside Hotel\n",
      "Description: Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.\n",
      "Caption: <em>Save up to 50% off traditional hotels.</em> <em>Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, </em>bowling<em> alley, fitness center </em>and more.\n",
      "\n",
      "1.7596698999404907\n",
      "13\n",
      "Luxury Lion Resort\n",
      "Description: Unmatched Luxury. Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium and transportation hubs, we feature the best in convenience and comfort.\n",
      "Caption: Unmatched Luxury. Visit our<em> downtown </em>hotel to indulge in<em> luxury accommodations.</em> Moments from the stadium and transportation hubs, we feature the best in convenience and comfort.\n",
      "\n",
      "1.7341481447219849\n",
      "44\n",
      "Friendly Motor Inn\n",
      "Description: Close to historic sites, local attractions, and urban parks. Free Shuttle to the airport and casinos. Free breakfast and WiFi.\n",
      "Caption: <em>Close to historic sites, </em>local<em> attractions, and urban parks.</em> Free Shuttle to the airport and casinos. Free breakfast and WiFi.\n",
      "\n",
      "1.7327302694320679\n",
      "19\n",
      "Economy Universe Motel\n",
      "Description: Local, family-run hotel in bustling downtown Redmond. We are a pet-friendly establishment, near expansive Marymoor park, haven to pet owners, joggers, and sports enthusiasts. Close to the highway and just a short drive away from major cities.\n",
      "Caption: Local,<em> family-run hotel </em>in<em> bustling downtown Redmond.</em> We are a pet-friendly establishment, near expansive Marymoor park, haven to pet owners, joggers, and sports enthusiasts. Close to the highway and just a short drive away from major cities.\n",
      "\n",
      "1.728476643562317\n",
      "22\n",
      "Lion's Den Inn\n",
      "Description: Full breakfast buffet for 2 for only $1. Excited to show off our room upgrades, faster high speed WiFi, updated corridors & meeting space. Come relax and enjoy your stay.\n",
      "Caption: Full breakfast buffet for 2 for only $1. Excited to show off our<em> room upgrades, faster high speed WiFi, updated corridors & meeting space.</em> Come relax and enjoy your stay.\n",
      "\n",
      "1.722805142402649\n",
      "11\n",
      "Royal Cottage Resort\n",
      "Description: Your home away from home. Brand new fully equipped premium rooms, fast WiFi, full kitchen, washer & dryer, fitness center. Inner courtyard includes water features and outdoor seating. All units include fireplaces and small outdoor balconies. Pets accepted.\n",
      "Caption: Your home away from home. Brand new<em> fully equipped premium rooms, fast WiFi, full kitchen, washer & dryer, fitness center.</em> Inner courtyard includes water features and outdoor seating. All units include fireplaces and small outdoor balconies. Pets accepted.\n",
      "\n",
      "1.71288001537323\n",
      "42\n",
      "Rock Bottom Resort & Campground\n",
      "Description: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and campground accommodations to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "Caption: Rock Bottom is nestled on 20 unspoiled acres on a private cove of Rock Bottom Lake. We feature both lodging and<em> campground accommodations </em>to suit just about every taste. Even though we are out of the traffic of the city, getting there is only a short drive away.\n",
      "\n",
      "1.710044264793396\n",
      "45\n",
      "Happy Lake Resort & Restaurant\n",
      "Description: The largest year-round resort in the area offering more of everything for your vacation – at the best value! What can you enjoy while at the resort, aside from the mile-long sandy beaches of the lake? Check out our activities sure to excite both young and young-at-heart guests. We have it all, including being named “Property of the Year” and a “Top Ten Resort” by top publications.\n",
      "Caption: The largest<em> year-round resort </em>in the area offering more of everything for your vacation – at the best value. What can you enjoy while at the resort, aside from the mile-long sandy beaches of the lake. Check out our activities sure to excite both young and young-at-heart guests. We have it all, including being named<em> “Property of </em>the Year” and a.\n",
      "\n",
      "1.6724704504013062\n",
      "40\n",
      "Trails End Motel\n",
      "Description: Only 8 miles from Downtown. On-site bar/restaurant, Free hot breakfast buffet, Free wireless internet, All non-smoking hotel. Only 15 miles from airport.\n",
      "Caption: <em>Only 8 miles from Downtown.</em> <em>On-site bar/restaurant, Free hot breakfast buffet, Free wireless internet, All non-smoking hotel.</em> Only 15 miles from airport.\n",
      "\n",
      "1.6646721363067627\n",
      "47\n",
      "Country Comfort Inn\n",
      "Description: Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering reasonable rates and all the comforts home inlcuding living room suites and functional kitchens. Pets are welcome.\n",
      "Caption: Situated conveniently at the north end of the village, the inn is just a short walk from the lake, offering<em> reasonable </em>rates and all the comforts<em> home inlcuding living room suites and functional kitchens.</em> Pets are welcome.\n",
      "\n",
      "1.6575827598571777\n",
      "34\n",
      "Lakefront Captain Inn\n",
      "Description: Every stay starts with a warm cookie. Amenities like the Counting Sheep sleep experience, our Wake-up glorious breakfast buffet and spacious workout facilities await.\n",
      "Caption: Every stay starts with a warm cookie. <em>Amenities </em>like the<em> Counting Sheep sleep experience, </em>our<em> Wake-up glorious breakfast buffet </em>and<em> spacious workout facilities </em>await.\n",
      "\n",
      "1.6561648845672607\n",
      "26\n",
      "Planetary Plaza & Suites\n",
      "Description: Extend Your Stay. Affordable home away from home, with amenities like free Wi-Fi, full kitchen, and convenient laundry service.\n",
      "Caption: Extend Your Stay. <em>Affordable </em>home<em> away from home, </em>with<em> amenities </em>like<em> free Wi-Fi, full kitchen, and convenient laundry service.</em>\n",
      "\n",
      "1.5916515588760376\n",
      "6\n",
      "King's Cellar Hotel\n",
      "Description: Newest kid on the downtown block. Steps away from the most popular destinations in downtown, enjoy free WiFi, an indoor rooftop pool & fitness center, 24 Grab'n'Go & drinks at the bar\n",
      "Caption: Newest kid on the downtown block. Steps away from the most popular destinations in downtown, enjoy<em> free WiFi, an indoor rooftop pool & fitness center, </em>24 Grab'n'Go & drinks at the bar.\n",
      "\n",
      "1.5590404272079468\n",
      "3\n",
      "Gastronomic Landscape Hotel\n",
      "Description: The Gastronomic Hotel stands out for its culinary excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.\n",
      "Caption: The<em> Gastronomic </em>Hotel stands out for its culinary excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.\n",
      "\n",
      "1.5398989915847778\n",
      "21\n",
      "Good Business Hotel\n",
      "Description: 1 Mile from the airport. Free WiFi, Outdoor Pool, Complimentary Airport Shuttle, 6 miles from Lake Lanier & 10 miles from downtown. Our business center includes printers, a copy machine, fax, and a work area.\n",
      "Caption: 1 Mile from the airport. <em>Free WiFi, Outdoor Pool, Complimentary Airport Shuttle, 6 miles from Lake Lanier & 10 miles from downtown.</em> Our business center includes printers, a copy machine, fax, and a work area.\n",
      "\n",
      "1.4484460353851318\n",
      "48\n",
      "Nordick's Valley Motel\n",
      "Description: Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer. Hiking? Wine Tasting? Exploring the caverns? It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.\n",
      "Caption: Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer. Hiking? Wine Tasting. Exploring the caverns. It's all nearby and we have specially priced packages to help make our<em> B&B </em>your home base for fun while visiting the valley.\n",
      "\n",
      "1.231510877609253\n",
      "43\n",
      "Johnson's Family Resort\n",
      "Description: Family oriented resort located in the heart of the northland. Operated since 1962 by the Smith family, we have grown into one of the largest family resorts in the state. The home of excellent Smallmouth Bass fishing with 10 small cabins, we're a home not only to fishermen but their families as well. Rebuilt in the early 2000's, all of our cabins have all the comforts of home. Sporting a huge beach with multiple water toys for those sunny summer days and a Lodge full of games for when you just can't swim anymore, there's always something for the family to do. A full marina offers watercraft rentals, boat launch, powered dock slips, canoes (free to use), & fish cleaning facility. Rent pontoons, 14' fishing boats, 16' fishing rigs or jet ski's for a fun day or week on the water. Pets are accepted in the lakeside cottages.\n",
      "Caption: Family<em> oriented resort </em>located in the heart of the northland. Operated since 1962 by the Smith family, we have grown into one of the largest family resorts in the state. The home of excellent Smallmouth Bass fishing with 10 small cabins, we're a home not only to fishermen but their families as well. Rebuilt in the early 2000's, all of our cabins.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Run a semantic query that returns semantic answers  \n",
    "results =  search_client.search(query_type='semantic', semantic_configuration_name='semantic-config',\n",
    " search_text=\"what's a good hotel for people who like to read\",\n",
    " select='HotelId,HotelName,Description', query_caption='extractive', query_answer=\"extractive\",)\n",
    "\n",
    "semantic_answers = results.get_answers()\n",
    "for answer in semantic_answers:\n",
    "    if answer.highlights:\n",
    "        print(f\"Semantic Answer: {answer.highlights}\")\n",
    "    else:\n",
    "        print(f\"Semantic Answer: {answer.text}\")\n",
    "    print(f\"Semantic Answer Score: {answer.score}\\n\")\n",
    "\n",
    "for result in results:\n",
    "    print(result[\"@search.reranker_score\"])\n",
    "    print(result[\"HotelId\"])\n",
    "    print(result[\"HotelName\"])\n",
    "    print(f\"Description: {result['Description']}\")\n",
    "\n",
    "    captions = result[\"@search.captions\"]\n",
    "    if captions:\n",
    "        caption = captions[0]\n",
    "        if caption.highlights:\n",
    "            print(f\"Caption: {caption.highlights}\\n\")\n",
    "        else:\n",
    "            print(f\"Caption: {caption.text}\\n\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clean up"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you're finished with this index, you can delete it by running the following lines. Deleting unnecessary indexes frees up space for stepping through more quickstarts and tutorials."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    result = index_client.delete_index(index_name)\n",
    "    print ('Index', index_name, 'Deleted')\n",
    "except Exception as ex:\n",
    "    print (ex)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confirm the index deletion by running the following script that returns the index definition. If hotels-sample-index isn't returned, you've successfully deleted the index and have completed this quickstart."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    result = index_client.get_index(index_name)\n",
    "    print (result)\n",
    "except Exception as ex:\n",
    "    print (ex)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
